$(document).ready(function() {

	var GlobalBean = {
		displayChartCount : 0,
		displayChartPointCount : 0,
		page : new Page(),
		selectedChart : {},
		filterCondition : {},
		chartCollenction : [],
        opeKey : null,
        NORMAL : "0000000"
	};

	var DocBean = {
		buttons : {
			queryBtn : {
				ID : $("#f1_btn"),
				clickFnc : function() {
					DocBean.dialogs.queryDialog.showFnc();
				}
			},
			calcCPKBtn : {
				ID : $("#f5_btn"),
				calcCpkFnc : function() {
					var calChart, i;
					
					if (GlobalBean.page.chartCount <= 0) {
						showErrorDialog("", "请选择需要管制图后再计算");
						return false;
					}

					for (i = 0; i < GlobalBean.page.chartCount; i++) {
						if (GlobalBean.page.chartList[i].chart_typ == _CHART_TYPE_MEAN
								|| GlobalBean.page.chartList[i].chart_typ == _CHART_TYPE_SINGLE) {
							calChart = GlobalBean.page.chartList[i];
							break;
						}
					}
					calChart.caclCPk();
					DocBean.dialogs.calCpkDialog.showDialogFnc(calChart);
				}
			},
			clearBtn : {
                ID : $("#f10_btn"),
                clickFnc : function() {
                    var f = document.getElementById("canvastotal");
                    var childs = f.childNodes;
                    if(childs.length > 0){
                        for(var i = childs.length - 1; i >= 0; i--) {
							/*  alert(childs[i].nodeName);*/
                            f.removeChild(childs[i]);
                        }
                        GlobalBean.displayChartCount = 0;
                        GlobalBean.page = new Page();
                        //$("input:not(.noreset)").val("");
                    }

                    var rawDataDiv = document.getElementById("rawDataDiv");
                    var rawDataDivchilds = rawDataDiv.childNodes;
                    if(rawDataDivchilds.length > 0){
                        for(var i = rawDataDivchilds.length - 1; i >= 0; i--) {
							/*  alert(childs[i].nodeName);*/
                            rawDataDiv.removeChild(rawDataDivchilds[i]);
                        }
                    }

                    var chartDataDiv = document.getElementById("chartDataDiv");
                    var chartDataDivchilds = chartDataDiv.childNodes;
                    if(chartDataDivchilds.length > 0){
                        for(var i = chartDataDivchilds.length - 1; i >= 0; i--) {
							/*  alert(childs[i].nodeName);*/
                            chartDataDiv.removeChild(chartDataDivchilds[i]);
                        }
                    }

                    //汇总是拼上去的
                    var sumaryDiv = document.getElementById("sumaryDiv");
                    if(sumaryDiv !== null){
                        var sumaryDivchilds = sumaryDiv.childNodes;
                        if(sumaryDivchilds.length > 0){
                            for(var i = sumaryDivchilds.length - 1; i >= 0; i--) {
								/*  alert(childs[i].nodeName);*/
                                sumaryDiv.removeChild(sumaryDivchilds[i]);
                            }
                        }
                    }

                    //
                    // initSelectFnc.iniCusIdSel();
                    // initSelectFnc.initmdlId();
                    // initSelectFnc.initWoIdFnc();
                    // initSelectFnc.iniOpeSelect();
                    // initSelectFnc.iniToolSel();

					/*var chart = new Chart();
					 // var currentWidth = GlobalBean.displayChartPointCount *
					 // chart.initializeCanvas("chart", 1222, 550);
					 var canvas = $("#chart");
					 canvas.get(0).getContext("2d").clearRect(0, 0,
					 canvas.width(), canvas.height());
					 GlobalBean.displayChartCount = 0;
					 GlobalBean.page = new Page();
					 $("input:not(.noreset)").val("");*/

					/*    if ($("#sumaryDiv").length > 0) {
					 $("#sumaryDiv").remove();
					 }
					 if ($("#chartDataDiv").length > 0) {
					 $("#chartDataDiv").remove();
					 }
					 if ($("#rawDataDiv").length > 0) {
					 $("#rawDataDiv").remove();
					 }*/				}
			},
			filterBtn : {
				ID : $("#f2_btn"),
				clickFnc : function() {

				}
			},
			refreshBtn : {
				ID : $("#f3_refresh_btn"),
				clickFnc : function() {
					DocBean.buttons.clearBtn.clickFnc();
					var length = GlobalBean.chartCollenction.length;
					for(var i = 0; i < length; i++){
                        //新建N个canvas
                        var canvas = document.createElement('canvas');
                        //按顺序设置ID
                        var chartName = "chart" + i;
                        canvas.setAttribute("id",chartName);
                        document.getElementById("canvastotal").appendChild(canvas);
                        showChart({
                            col_typ_fk : GlobalBean.chartCollenction[i].col_typ_fk,
                            grp_no_fk : GlobalBean.chartCollenction[i].grp_no_fk,
                            chart_no : GlobalBean.chartCollenction[i].chart_no
                        }, true,true,length,chartName);

                        //showChart(rowData, true,"Y",length,chartName);
                       /* showChart({
                            col_typ_fk : GlobalBean.selectedChart.col_typ,
                            grp_no_fk : GlobalBean.selectedChart.grp_no,
                            chart_no : GlobalBean.selectedChart.chart_no
                        }, true,true);*/
					}


				}
			}
		},
		dialogs : {
			queryDialog : {
				ID : $("#queryDialog"),
				initFnc : function() {
					var queryDialog;
					var inObj,outObj,iary={};
					queryDialog = DocBean.dialogs.queryDialog;

					queryDialog.ID.modal({
								backdrop : 'static',
								keyboard : false,
								show : false
							});

					// $("input").val("");
					// $("select").empty();
                    $("#queryDialog_grpNameSel").empty();

					// queryDialog.ID.unbind('shown');
					queryDialog.buttons.queryBtn.unbind('click');
					queryDialog.elements.grpNameSel.ID.unbind("change");
					// queryDialog.ID.bind('shown', queryDialog.showFnc);
					queryDialog.buttons.queryBtn.bind('click',
							queryDialog.buttons.queryBtnClickFnc);
					queryDialog.elements.grpNameSel.ID.bind("change",
							queryDialog.elements.grpNameSel.onChangeFnc);

					queryDialog.buttons.queryMerge.unbind('click');
					queryDialog.buttons.queryMerge.bind('click',
							queryDialog.buttons.queryMergeFnc);
//					url = "listAllGroupMain";
//					outTrx = comSendAjax(_GET, url).outPo;
					iary={
						grp_no:null
					}
					inObj={
						trx_id: "FQPGRPMN",
						action_flg:"Q",
						iary:[iary]
					}
					outObj = comTrxSubSendPostJson(inObj);
					if (outObj.rtn_code == _NORMAL) {

						for (i = 0; i < outObj.oary.length; i++) {
                            SelectDom.addSelect($("#queryDialog_grpNameSel"),outObj.oary[i].col_typ +":"+ outObj.oary[i].grp_no,outObj.oary[i].grp_name);
						}
						queryDialog.elements.grpNameSel.onChangeFnc();

					}

				},
				showFnc : function() {
					var queryDialog, url, outTrx;

					queryDialog = DocBean.dialogs.queryDialog;

					queryDialog.ID.modal("show");

					queryDialog.initFnc();

				},
				elements : {
					grpNameSel : {
						ID : $("#queryDialog_grpNameSel"),
						onChangeFnc : function() {
							var grp_no, url, inTrx, ouTrx,iary={};
							//3:000006  先设置成 管制图类型 : 管制图组编号
							grp_no = DocBean.dialogs.queryDialog.elements.grpNameSel.ID.val();
							var colTypGrpNo = [];
                            colTypGrpNo = grp_no.split(":");
//							url = "querySPCChartMainByCrit";
							iary={
								col_typ_fk : colTypGrpNo[0],
								grp_no_fk : grp_no=="undefined"?null:colTypGrpNo[1]
							}
							inTrx = {
								trx_id  :"FQPCHTMN",
								action_flg:"Q",
								iary:[iary]
							};
//							var ouTrx = comSendAjax(_POST, url, inTrx).outPo;
							var ouTrx = comTrxSubSendPostJson(inTrx);
							if (ouTrx.rtn_code == _NORMAL) {
								setGridInfo(ouTrx.oary, '#chartListGrd');
							}
						}
					}

				},
				buttons : {
					queryBtn : $("#queryDialog_queryBtn"),
                    queryMerge : $("#queryMerge"),
					queryBtnClickFnc : function() {
                        GlobalBean.chartCollenction.splice(0,GlobalBean.chartCollenction.length);//清空数组
						var selRow, rowData;
                        var ids = $("#chartListGrd").jqGrid('getGridParam','selarrrow');
                       	if(ids.length == 0){
                       		showErrorDialog("","请至少选择一个管制图编号！再查询！");
                       		return false;
						}

						DocBean.buttons.clearBtn.clickFnc();
						var length = ids.length;
						for(var i = 0 ;i < ids.length; i++){
							//新建N个canvas
							var canvas = document.createElement('canvas');
							//按顺序设置ID
							var chartName = "chart" + i;
                            canvas.setAttribute("id",chartName);
							document.getElementById("canvastotal").appendChild(canvas);
							var rowData = $('#chartListGrd').jqGrid("getRowData",ids[i]);
                            GlobalBean.chartCollenction.push(rowData);
                            // showChart(rowData, true,"Y",length,chartName);
						}
                        filter("Y");//根据条件查询chart图
                        $('#queryDialog').modal("hide");
					},

					queryMergeFnc :function () {
                        var ids = $("#chartListGrd").jqGrid('getGridParam','selarrrow');
                        if(ids.length < 1){
                            showErrorDialog("","请至少选择两个管制图编号！再查询！");
                            return false;
                        }
                        var dataARRAY = [];
                        var obj;
                        for(var i = 0;i < ids.length; i++){
                            var rowData = $("#chartListGrd").jqGrid("getRowData",ids[i]);
                            obj = checkMoreAndShow(rowData,true,true);
                            dataARRAY.push(obj.dataArray);
                        }

                        bulidchart(obj.count,dataARRAY);
                        $('#queryDialog').modal("hide");
                    }
				}
			},
			calCpkDialog : {
				ID : $("#calCpkDialog"),
				elements : {
					meanTxt : $("#meanTxt"),
					stdDevTxt : $("#stdDevTxt"),
					sigmaTxt : $("#sigmaTxt"),
					caTxt : $("#caTxt"),
					cpTxt : $("#cpTxt"),
					cpkTxt : $("#cpkTxt"),
					ppTxt : $("#ppTxt"),
					ppkTxt : $("#ppkTxt"),
					gradeTxt : $("#gradeTxt")
				},
				initDialogFnc : function(calChart) {
					var dialogElems = DocBean.dialogs.calCpkDialog.elements;

					$("#calCpkDialogForm input").val("");

					dialogElems.meanTxt.val(calChart.mean);
					dialogElems.sigmaTxt.val(calChart.sigma);
					dialogElems.caTxt.val(calChart.ca);
					dialogElems.cpTxt.val(calChart.cp);
					dialogElems.cpkTxt.val(calChart.cpk);
					dialogElems.ppTxt.val(calChart.pp);
					dialogElems.ppkTxt.val(calChart.ppk);
					dialogElems.gradeTxt.val(calChart.grade);
				},
				showDialogFnc : function(calChart) {
					var calCpkDialog = DocBean.dialogs.calCpkDialog;
					calCpkDialog.ID.modal({
								backdrop : 'static',
								keyboard : false,
								show : false
							});
					calCpkDialog.ID.unbind('shown');
					calCpkDialog.ID.bind('shown', function() {
								calCpkDialog.initDialogFnc(calChart);
							}());
					calCpkDialog.ID.modal("show");
				},
				buttons : {

				}

			},
			filterChartDialog : {
				ID : $("#filterChartDialog"),
				elements : {
					mdlIDTxt : $("#filterChart_mdlIDSel"),
					eqptIDSel : $("#filterChart_eqptIDSel"),
					fromTimeIDTxt : $("#filterChart_fromTimeIDTxt"),
					toTimeIDTxt : $("#filterChart_toTimeIDTxt")
				},
				initDialogFnc : function(calChart) {
					var dialogElems = DocBean.dialogs.filterChartDialog.elements;

					dialogElems.eqptIDSel
					dialogElems.sigmaTxt.val(calChart.sigma);
					dialogElems.caTxt.vt.val(calChart.grade);
				},
				showDialogFnc : function(calChart) {
					var filterChartDialog = DocBean.dialogs.filterChartDialog;
					filterChartDialog.ID.modal({
								backdrop : 'static',
								keyboard : false,
								show : false
							});
					filterChartDialog.ID.unbind('shown');
					filterChartDialog.ID.bind('shown', function() {
								filterChartDialog.initDialogFnc(calChart);
							});
					filterChartDialog.ID.modal("show");
				},
				buttons : {

				}
			}
		},
		grids : {
			chartGrid : {
				initFnc : function() {
					var grdInfoCM = [{
								name : 'col_typ_fk',
								index : 'col_typ_fk',
								label : '数据类型',
								width : 50,
								hidden : true
							}, {
								name : 'grp_no_fk',
								index : 'grp_no_fk',
								label : '管制组代码',
								width : 120,
								hidden : true

							}, {
								name : 'chart_no',
								index : 'chart_no',
								label : '管制图编号',
								width : 200
							}, {
								name : 'data_group_fk',
								index : 'data_group_fk',
								label : '量测名称',
								size : 120
							}, {
								name : 'chart_typ',
								index : 'chart_typ',
								label : '管制图类型',
								size : 200
							}, {
								name : 'chart_sub_typ',
								index : 'chart_sub_typ',
								size : 200,
								hidden : true
							}, {
								name : 'chart_name',
								index : 'chart_name',
								label : '管制图名称',
								size : '120px'
							}, {
								name : 'chart_dsc',
								index : 'chart_dsc',
								label : '管制图描述',
								size : '150px'
							}, {
								name : 'chart_owner',
								index : 'chart_owner',
								label : '管制图负责人',
								size : '100px'
							}, {
								name : 'sample_size',
								index : 'sample_size',
								label : '样本数',
								size : '200px',
								hidden : true
							}, {
								name : 'max_chart_point',
								index : 'max_chart_point',
								label : '最大接收点数',
								size : '80px'
							}, {
								name : 'raw_keep_flg',
								index : 'raw_keep_flg',
								label : '保留原数据',
								size : '200px',
								hidden : true
							}, {
								name : 'evt_usr',
								index : 'evt_usr',
								label : '事件用户',
								size : '120px',
								sortable : true
							}, {
								name : 'evt_timestamp',
								index : 'evt_timestamp',
								label : '事件时间',
								size : '120px'
							}

					];

					$("#chartListGrd").jqGrid({
						url : "",
						datatype : "local",
						mtype : "POST",
						shrinkToFit : false,
						scroll : true,
						rownumWidth : true,
						resizable : true,
						rowNum : 40,
						loadonce : true,
						fixed : true,
						viewrecords : true,
                        multiselect : true,
						colModel : grdInfoCM,
						onSelectRow : function(rowId) {
						/*	var selRowData = $(this)
									.jqGrid("getRowData", rowId);
							DocBean.buttons.clearBtn.clickFnc();
							showChart(selRowData, true,'Y');
							$('#queryDialog').modal("hide");*/
						}
					});

				}
			}
		}
	};

	// $("#main #chartList ul li").click(queryDialog_queryBtnfunction() {

	function setFilterCondition(pointArray) {
		var i, point, cusIdMap, mdlIdMap, woIdMap, lotIdMap, opeIdMap, toolIdMap;
		var cusId, mdlId, woId, lotId, pToolId, pOpeId;

		cusId = $("#cusIdSel").val();
		mdlId = BaseFnc.returnSpace($("#mdlIdSel").val());
		woId = $("#woIdSel").val();
		lotId = $("#lotIdSel").val();
		pToolId = $("#eqptIdSel").val();
		pOpeId = $("#opeIdSel").val();

		cusIdMap = {};
		mdlIdMap = {};
		woIdMap = {};
		lotIdMap = {};
		opeIdMap = {};
		toolIdMap = {};

		$("#mdlIdSel").empty();
		$("#mdlIdSel").append("<option value=''> </option>");

		for (i = 0; i < pointArray.length; i++) {
			point = pointArray[i];
			if (point.cus_id_fk)
				cusIdMap[point.cus_id_fk] = point.cus_id_fk;
			if (point.wo_id_fk)
				// woIdMap[wo_id_fk] = point.wo_id_fk;
				woIdMap[point.wo_id_fk] = point.wo_id_fk; // NO.03
			if (point.lot_id_fk)
				// lotIdMap[lot_id_fk] = point.lot_id_fk;
				lotIdMap[point.lot_id_fk] = point.lot_id_fk; // NO.03
			if (point.mdl_id_fk)
				mdlIdMap[point.mdl_id_fk] = point.mdl_id_fk;
			if (point.p_ope_id_fk)
				opeIdMap[point.p_ope_id_fk] = point.p_ope_id_fk;
			if (point.p_tool_id_fk)
				toolIdMap[point.p_tool_id_fk] = point.p_tool_id_fk;
		}

		// mdl id special process
		for (var pro in mdlIdMap) {
			var tmpMdlId = mdlIdMap[pro];
			var mdlIdFormated = BaseFnc.replaceSpace(tmpMdlId);
			$("#mdlIdSel").append("<option value= " + mdlIdFormated + ">"
					+ tmpMdlId + "</option>");
		}

		$("#mdlIdSel").val(BaseFnc.replaceSpace(mdlId));

		setSelectionByMap($("#cusIdSel"), cusIdMap, cusId);
		setSelectionByMap($("#opeIdSel"), opeIdMap, pOpeId);
		setSelectionByMap($("#eqptIdSel"), toolIdMap, pToolId);
		setSelectionByMap($("#lotIdSel"), lotIdMap, lotId); // NO.03
		setSelectionByMap($("#woIdSel"), woIdMap, woId); // NO.03
	}

	function setSelectionByMap($domObj, map, originValue) {
		$domObj.empty();
		$domObj.append("<option option=''> </optoin>");
		for (var pro in map) {
			$domObj.append("<option value= " + map[pro] + ">" + map[pro]
					+ "</option>");
		}
		if (typeof(originValue) !== "undefined") {
			$domObj.val(originValue);
		}
	};

	function checkMoreAndShow(selectChartGridData,setConditionFlg,firstFlg) {
        var dataArray2 = new Array();
        dataArray2.splice(0,dataArray2.length);
		var count = 0;
        var iary = {
            col_typ_fk : selectChartGridData.col_typ_fk,
            grp_no_fk : selectChartGridData.grp_no_fk,
            chart_no : selectChartGridData.chart_no,
        };

        var querySettingObj = {
            trx_id :"FQPCHTMN",
            action_flg:"I",
            iary : [iary]
        };

        GlobalBean.selectedChart.col_typ = selectChartGridData.col_typ_fk;
        GlobalBean.selectedChart.grp_no = selectChartGridData.grp_no_fk;
        GlobalBean.selectedChart.chart_no = selectChartGridData.chart_no;
        GlobalBean.selectedChart.chart_typ = selectChartGridData.chart_typ;

        var outTrxObj = comTrxSubSendPostJson(querySettingObj);
        var chartSettingOary = outTrxObj.oaryB;

        var summaryObj = {};
        for (var i = 0; i < chartSettingOary.length; i++) {
            // for(var i=0;i<1;i++){
            var data = new Object();
            data.upl = chartSettingOary[i].chart_upl;
            data.usl = chartSettingOary[i].chart_usl;
            data.ucl = chartSettingOary[i].chart_ucl;
            data.target = chartSettingOary[i].chart_target;
            data.lcl = chartSettingOary[i].chart_lcl;
            data.lsl = chartSettingOary[i].chart_lsl;
            data.lpl = chartSettingOary[i].chart_lpl;
            data.cname = chartSettingOary[i].chart_name;
            data.ctitle = chartSettingOary[i].chart_dsc;
            //chart图单位
			data.cunit = chartSettingOary[i].chart_unit;
            data.chart_typ = chartSettingOary[i].chart_typ_fk;
            data.gname = chartSettingOary[i].grp_name;
            //chart图间隔
			data.chart_space  = chartSettingOary[i].chart_space;

            chartTyp = chartSettingOary[i].chart_typ_fk;

            data.point = new Array();
            // 查询 chart_data
            var queryObj2 = {
                trx_id :"XPCCHTDT",
                action_flg:"L",
                col_typ : selectChartGridData.col_typ_fk,
                grp_no : selectChartGridData.grp_no_fk,
                chart_no : selectChartGridData.chart_no,
                chart_typ : chartSettingOary[i].chart_typ_fk,
                first_flg : firstFlg
            };
            if (selectChartGridData.cus_id) {
                queryObj2.cus_id = selectChartGridData.cus_id;
            }
            if (selectChartGridData.mdl_id) {
                queryObj2.mdl_id = selectChartGridData.mdl_id;
            }
            if (selectChartGridData.wo_id) {
                queryObj2.wo_id = selectChartGridData.wo_id;
            }
			/*if (selectChartGridData.lot_id) {
			 queryObj2.lot_id = selectChartGridData.lot_id;
			 }*/
            if (selectChartGridData.p_tool_id) {
                queryObj2.p_tool_id = selectChartGridData.p_tool_id;
            }
            if (selectChartGridData.p_ope_id) {
                queryObj2.p_ope_id = selectChartGridData.p_ope_id;
            }
            if (selectChartGridData.input_timestamp_from) {
                queryObj2.input_timestamp_from = selectChartGridData.input_timestamp_from;
            }
            if (selectChartGridData.input_timestamp_to) {
                queryObj2.input_timestamp_to = selectChartGridData.input_timestamp_to;
            }
//			queryObj2.limit_flg = limitFlg ? "Y" : "N" ;

            queryObj2.limit_flg = "Y";
            queryObj2.count = 200;
            // queryObj2.limit_flg = limitFlg ? "Y" : "N";
//			var url = "queryChartDataByCrit";
//			var outTrxObj2 = comSendAjax(_POST, url, queryObj2);
            var outTrxObj2 = comTrxSubSendPostJson(queryObj2);
            if (outTrxObj2.rtn_code != _NORMAL) {
                // TODO
                alert("查询失败" + outTrxObj2.rtn_mesg);
                return false;
            }

            var dataList = outTrxObj2.oary2;

            var tempDataCnt = dataList.length < 200 ? dataList.length : 200;// add
            // point
            // toplimit
            // ---bailang
            if (selectChartGridData.input_timestamp_from) {
                tempDataCnt = dataList.length;
            }
            for (var j = 0; j < tempDataCnt; j++) {
                // for (var j = 0; j < dataList.length; j++) {
                var point = new Object();
                var chartData = dataList[j];

                point.inputTimestamp = chartData.input_timestamp;
                // point.value = Math.ceil(Math.random() * 200 + 150);
                point.value = chartData.chart_value;
                point.glassId = chartData.prd_seq_id_fk;
                point.processEqptId = chartData.p_tool_id_fk;
                point.measurementEqptId = chartData.m_tool_id_fk;
                point.comment = chartData.chart_comment;
                point.reporter = chartData.evt_usr;
                point.chart_rule1_rlt_fk = chartData.chart_rule1_rlt_fk;
                point.chart_spec_rlt_fk = chartData.chart_rule1_rlt_fk;
                point.proc_timestamp = chartData.proc_timestamp; // NO.03
                point.wo_id_fk = chartData.wo_id_fk;
                point.cus_id_fk = chartData.cus_id_fk;
                point.so_id_fk = chartData.so_id_fk;
				/*point.lot_id_fk = chartData.lot_id_fk;*/
                point.chart_rule_1_rlt = chartData.chart_rule1_rlt_fk;
                point.col_typ_fk = chartData.col_typ_fk;
                point.grp_no_fk = chartData.grp_no_fk;
                point.chart_no_fk = chartData.chart_no_fk;
                point.chart_typ_fk = chartData.chart_typ_fk;
                point.input_time_d = chartData.input_time_d;
                point.ucl = chartData.chart_ucl_fk;
                point.lcl = chartData.chart_lcl_fk;


                point = $.extend(point, chartData);
                // liufang add median chart
                if (chartTyp == "01" || chartTyp == '30') {
                    //MEAN                  //MEDIAN
                    point.rawData = dataList[j].rawDataList;
                    point.rawDataList = dataList[j].rawDataList;
                }
                data.point.push(point);
            }
			//显示图下方的数据汇总
       /*     if (chartTyp == "01" || chartTyp == "10" || chartTyp == '30'
                || chartTyp == '40' || chartTyp == '50' || chartTyp == '60') {
                if (setConditionFlg == true) {
                    setFilterCondition(dataList);
                    GlobalBean.displayChartPointCount = data.point.length;
                }
                if (chartTyp === "01") {
                    clearRawDataGrd();
                    fillRawDataGrd(data.point, data.usl, data.lsl);
                } else {
                    clearRawDataGrd();
                }
                fillChatDataGrd(data.point);
                summaryObj.mainChartSetting = chartSettingOary[i];
                summaryObj.mainChartPointArr = data.point;
            } else {
                fillChartDataGrdBySlaveChartData(data.point);
                summaryObj.slaveChartSetting = chartSettingOary[i];
                summaryObj.slaveChartPointArr = data.point;
            }*/
            dataArray2.push(data);
            GlobalBean.displayChartCount++;
            count++;
        }
        var obj = new Object();
        obj.dataArray = dataArray2;
        obj.count = count;
        //汇总数据
        //fillSummaryDataGrd(summaryObj);
        return obj;
    };

	// 将几组不同的数据放在第一组数据的图中
	function bulidchart(Count,dataARRAY){
		var dataArray1 = dataARRAY[0];//chart图显示第一组的图，其他两张默认共用同一张图
        switch (Count) {
            case 1 :
                var chart = new Chart();
                chart.initializeCanvas("chart", 1222, 550, false,
                    dataArray1[0].point.length);
                chart.initializeChart(dataArray1[0], 1, 1);
                if(typeof(dataArray1[0].ucl)=="undefined" && dataArray1[0].point.length > 25){
                    chart.drawCL();
                }
                //drawHistogram();
                for(var i = 0;i < dataARRAY.length;i++){
                	var dataArray = dataARRAY[i];
                    chart.drawPoint(dataARRAY[i][0]);
				}
                chart.activateClickEvent();
                break;

            case 2 :
                var chart1 = new Chart();
                // setCanvasWidth(dataArray[0].point.length);
                chart1.initializeCanvas("chart", 1222, 550, false,
                    dataArray1[0].point.length);
                chart1.initializeChart(dataArray1[0], 2, 1);

                if(typeof(dataArray1[0].ucl)=="undefined" && dataArray1[0].point.length > 25){
                    chart1.drawCL();
                }
                //drawHistogram();
                for(var i = 0;i < dataARRAY.length;i++){
                    var dataArray = dataARRAY[i];
                    chart1.drawPoint(dataARRAY[i][0]);
                }
                chart1.activateClickEvent();

                // fix bug
                var chart2 = new Chart();
                // setCanvasWidth(dataArray[0].point.length);
                chart2.initializeCanvas("chart", 1222, 550, true,
                    dataArray1[0].point.length);
                chart2.initializeChart(dataArray1[1], 2, 2);
                for(var i = 0;i < dataARRAY.length;i++){
                    chart2.drawPoint(dataARRAY[i][1]);
                }
                chart2.activateClickEvent();
                GlobalBean.page.addChart(chart1);
                GlobalBean.page.addChart(chart2);
                GlobalBean.page.activateClickEvent();
                break;

            case 3 :
                var chart1 = new Chart();
                chart1.initializeCanvas("chart", 1222, 550, false,
                    dataArray1[0].point.length);
                chart1.initializeChart(dataArray1[0], 3, 1);
                if(typeof(dataArray1[0].ucl)=="undefined" && dataArray1[0].point.length > 25){
                    chart1.drawCL();
                }
                //drawHistogram();
                for(var i = 0;i < dataARRAY.length;i++){
                    chart1.drawPoint(dataARRAY[i][0]);
                }
                chart1.activateClickEvent();

                var chart2 = new Chart();
                chart2.initializeCanvas("chart", 1222, 550, true,
                    dataArray1[0].point.length);
                chart2.initializeChart(dataArray1[1], 3, 2);
                for(var i = 0;i < dataARRAY.length;i++){
                    chart2.drawPoint(dataARRAY[i][1]);
                }
                chart2.activateClickEvent();

                var chart3 = new Chart();
                chart3.initializeCanvas("chart", 1222, 550, true,
                    dataArray1[0].point.length);
                chart3.initializeChart(dataArray1[2], 3, 3);
                for(var i = 0;i < dataARRAY.length;i++){
                    chart3.drawPoint(dataARRAY[i][2]);
                }
                GlobalBean.page.addChart(chart1);
                GlobalBean.page.addChart(chart2);
                GlobalBean.page.addChart(chart3);
                GlobalBean.page.activateClickEvent();
                break;
        }
	};


    var dataArray = new Array();
	function showChart(selectChartGridData, setConditionFlg,firstFlg,length,chartName) {
	    //如果length = 0 -》正常show  ,如果length > 0,不需要汇总数据和子chart
        dataArray.splice(0,dataArray.length);
		var chartTyp, dataCnt;
		var iary = {
            col_typ_fk : selectChartGridData.col_typ_fk,
            grp_no_fk : selectChartGridData.grp_no_fk,
            chart_no : selectChartGridData.chart_no,
		};
		var querySettingObj = {
			trx_id :"FQPCHTMN",
			action_flg:"I",
			iary : [iary]
		};
		GlobalBean.selectedChart.col_typ = selectChartGridData.col_typ_fk;
		GlobalBean.selectedChart.grp_no = selectChartGridData.grp_no_fk;
		GlobalBean.selectedChart.chart_no = selectChartGridData.chart_no;
		GlobalBean.selectedChart.chart_typ = selectChartGridData.chart_typ;

//		var url = "querySPCChartSettingByCrit";
//		var outTrxObj = comSendAjax(_POST, url, querySettingObj).outPo;
		var outTrxObj = comTrxSubSendPostJson(querySettingObj);
		
		var chartSettingOary = outTrxObj.oaryB;
		//dataArray = new Array();
		var summaryObj = {};
		for (var i = 0; i < chartSettingOary.length; i++) {
			// for(var i=0;i<1;i++){
			var data = new Object();
			data.upl = chartSettingOary[i].chart_upl;
			data.usl = chartSettingOary[i].chart_usl;
			data.ucl = chartSettingOary[i].chart_ucl;
			data.target = chartSettingOary[i].chart_target;
			data.lcl = chartSettingOary[i].chart_lcl;
			data.lsl = chartSettingOary[i].chart_lsl;
			data.lpl = chartSettingOary[i].chart_lpl;
			data.cname = chartSettingOary[i].chart_name;
			data.ctitle = chartSettingOary[i].chart_dsc;
			data.cunit = chartSettingOary[i].chart_unit;
			data.chart_typ = chartSettingOary[i].chart_typ_fk;
			data.gname = chartSettingOary[i].grp_name;
            data.chart_space = chartSettingOary[i].chart_space;
			chartTyp = chartSettingOary[i].chart_typ_fk;

			data.point = new Array();
			// 查询 chart_data
			var queryObj2 = {
				trx_id :"XPCCHTDT",
				action_flg:"L",
				col_typ : selectChartGridData.col_typ_fk,
				grp_no : selectChartGridData.grp_no_fk,
				chart_no : selectChartGridData.chart_no,
				chart_typ : chartSettingOary[i].chart_typ_fk,
                first_flg : firstFlg
			};
			if (selectChartGridData.cus_id) {
				queryObj2.cus_id = selectChartGridData.cus_id;
			}
			if (selectChartGridData.mdl_id) {
				queryObj2.mdl_id = selectChartGridData.mdl_id;
			}
			if (selectChartGridData.wo_id) {
				queryObj2.wo_id = selectChartGridData.wo_id;
			}
			/*if (selectChartGridData.lot_id) {
				queryObj2.lot_id = selectChartGridData.lot_id;
			}*/
			if (selectChartGridData.p_tool_id) {
				queryObj2.p_tool_id = selectChartGridData.p_tool_id;
			}
			if (selectChartGridData.p_ope_id) {
				queryObj2.p_ope_id = selectChartGridData.p_ope_id;
			}

            if (selectChartGridData.fab_id_fk) {
                queryObj2.fab_id_fk = selectChartGridData.fab_id_fk;
            }

            if (selectChartGridData.line_id_fk) {
                queryObj2.line_id_fk = selectChartGridData.line_id_fk;
            }

            if (selectChartGridData.shift_id_fk) {
                queryObj2.shift_id_fk = selectChartGridData.shift_id_fk;
            }

            if (selectChartGridData.boat_number) {
                queryObj2.boat_number = selectChartGridData.boat_number;
            }

			if (selectChartGridData.input_timestamp_from) {
				queryObj2.input_timestamp_from = selectChartGridData.input_timestamp_from;
			}
			if (selectChartGridData.input_timestamp_to) {
				queryObj2.input_timestamp_to = selectChartGridData.input_timestamp_to;
			}
//			queryObj2.limit_flg = limitFlg ? "Y" : "N" ;
		    
			queryObj2.limit_flg = "Y";
			queryObj2.count = 200;
			// queryObj2.limit_flg = limitFlg ? "Y" : "N";
//			var url = "queryChartDataByCrit";
//			var outTrxObj2 = comSendAjax(_POST, url, queryObj2);
			var outTrxObj2 = comTrxSubSendPostJson(queryObj2);
			if (outTrxObj2.rtn_code != _NORMAL) {
				// TODO
				alert("查询失败" + outTrxObj2.rtn_mesg);
				return false;
			}

			//值和原始值 rawDataList
			var dataList = outTrxObj2.oary2;

			// var tempDataCnt = dataList.length > 200 ? dataList.length : 200;// add
			var tempDataCnt = dataList.length;
			// point
			// toplimit
			// ---bailang
			if (selectChartGridData.input_timestamp_from) {
				tempDataCnt = dataList.length;
			}
			for (var j = 0; j < tempDataCnt; j++) {
				// for (var j = 0; j < dataList.length; j++) {
				var point = new Object();
				var chartData = dataList[j];

				point.inputTimestamp = chartData.input_timestamp;
				// point.value = Math.ceil(Math.random() * 200 + 150);
				point.value = chartData.chart_value;
				point.glassId = chartData.prd_seq_id_fk;
				point.processEqptId = chartData.p_tool_id_fk;
				point.measurementEqptId = chartData.m_tool_id_fk;
				point.comment = chartData.chart_comment;
				point.reporter = chartData.evt_usr;
				point.chart_rule1_rlt_fk = chartData.chart_rule1_rlt_fk;
				point.chart_spec_rlt_fk = chartData.chart_rule1_rlt_fk;
				point.proc_timestamp = chartData.proc_timestamp; // NO.03
				point.wo_id_fk = chartData.wo_id_fk;
				point.cus_id_fk = chartData.cus_id_fk;
				point.so_id_fk = chartData.so_id_fk;
				/*point.lot_id_fk = chartData.lot_id_fk;*/
				point.chart_rule_1_rlt = chartData.chart_rule1_rlt_fk;
				point.col_typ_fk = chartData.col_typ_fk;
				point.grp_no_fk = chartData.grp_no_fk;
				point.chart_no_fk = chartData.chart_no_fk;
				point.chart_typ_fk = chartData.chart_typ_fk;
				point.input_time_d = chartData.input_time_d;
				point.ucl = chartData.chart_ucl_fk;
				point.lcl = chartData.chart_lcl_fk;

				point = $.extend(point, chartData);
				// liufang add median chart
				if (chartTyp == "01" || chartTyp == '30') {
					//MEAN                  //MEDIAN
					point.rawData = dataList[j].rawDataList;
					point.rawDataList = dataList[j].rawDataList;
				}
				data.point.push(point);
			}

			var dataArry = data.point;
			//mean图需要加最小值加最大值 已供右击显示
			if(typeof(point) !== "undefined" && point.chart_typ_fk == "01"){
			}

			if(length === 1){
                if (chartTyp == "01" || chartTyp == "10" || chartTyp == '30'
                    || chartTyp == '40' || chartTyp == '50' || chartTyp == '60') {
                    if (setConditionFlg == true) {
                        setFilterCondition(dataList);
                        GlobalBean.displayChartPointCount = data.point.length;
                    }
                    if (chartTyp === "01") {
                        clearRawDataGrd();
                        fillRawDataGrd(data.point, data.usl, data.lsl);
                    } else {
                        clearRawDataGrd();
                    }
                    fillChatDataGrd(data.point);
                    summaryObj.mainChartSetting = chartSettingOary[i];
                    summaryObj.mainChartPointArr = data.point;
                } else {
                    fillChartDataGrdBySlaveChartData(data.point);
                    summaryObj.slaveChartSetting = chartSettingOary[i];
                    summaryObj.slaveChartPointArr = data.point;
                }
            }else{
                if (chartTyp == "01" || chartTyp == "10" || chartTyp == '30'
                    || chartTyp == '40' || chartTyp == '50' || chartTyp == '60') {
                    if (setConditionFlg == true) {
                        setFilterCondition(dataList);// 设置查询条件的下拉框
                    }
                }
                //rawDataDiv
                $("#rawDataDiv").empty();
                //chartDataDiv
                $("#chartDataDiv").empty();
                if(document.getElementById("sumaryDiv")){
                    if ($("#sumaryDiv").length > 0) {
                        $("#sumaryDiv").remove();
                    }
				}
			}


			dataArray.push(data);
			//如果选择很多chart，不需要子chart
			if(length > 1){
                GlobalBean.displayChartCount = 1;
            }else{
                GlobalBean.displayChartCount++;
            }

		}
        if(length === 1){
            fillSummaryDataGrd(summaryObj);
        }


        $(this).toggleClass("chartListSelectedBackgroundColor");

		chartshow(GlobalBean.displayChartCount,dataArray,length,chartName);
	}

	function chartshow(count,dataArray,length,chartName){

        switch (count) {
            case 1 :
                    var chart = new Chart();
                	var height;
                    if(length > 1){
                        height = 550/2;
					}else{
                    	height = 550;
					}

                    chart.initializeCanvas(chartName, 1222, height, false,
                        dataArray[0].point.length);
                    chart.initializeChart(dataArray[0], 1, 1);
                    if(typeof(dataArray[0].ucl)=="undefined" && dataArray[0].point.length > 25){
                        chart.drawCL();
                    }
                    drawHistogram();
                    chart.drawPoint();
                	GlobalBean.page.addChart(chart,length);
                	GlobalBean.page.activateClickEvent(chartName,length);
                	break;

            case 2 :
                var chart1 = new Chart();
                // setCanvasWidth(dataArray[0].point.length);
                chart1.initializeCanvas(chartName, 1222, 550, false,
                    dataArray[0].point.length);
                chart1.initializeChart(dataArray[0], 2, 1);
                if(typeof(dataArray[0].ucl)=="undefined" && dataArray[0].point.length > 25){
                    chart1.drawCL();
                }
                drawHistogram();
                chart1.drawPoint();
                //chart1.activateClickEvent();

                // fix bug
                var chart2 = new Chart();
                // setCanvasWidth(dataArray[0].point.length);
                chart2.initializeCanvas(chartName, 1222, 550, true,
                    dataArray[0].point.length);
                chart2.initializeChart(dataArray[1], 2, 2);
                chart2.drawPoint();
                //chart2.activateClickEvent();
                GlobalBean.page.addChart(chart1,length);
                GlobalBean.page.addChart(chart2,length);
                GlobalBean.page.activateClickEvent(chartName,length);
                break;

            case 3 :
                var chart1 = new Chart();
                chart1.initializeCanvas(chartName, 1222, 550, false,
                    dataArray[0].point.length);
                chart1.initializeChart(dataArray[0], 3, 1);
                if(typeof(dataArray[0].ucl)=="undefined" && dataArray[0].point.length > 25){
                    chart1.drawCL();
                }
                drawHistogram();
                chart1.drawPoint();
                //chart1.activateClickEvent();

                var chart2 = new Chart();
                chart2.initializeCanvas(chartName, 1222, 550, true,
                    dataArray[0].point.length);
                chart2.initializeChart(dataArray[1], 3, 2);
                chart2.drawPoint();
                //chart2.activateClickEvent();

                var chart3 = new Chart();
                chart3.initializeCanvas(chartName, 1222, 550, true,
                    dataArray[0].point.length);
                chart3.initializeChart(dataArray[2], 3, 3);
                chart3.drawPoint();

                GlobalBean.page.addChart(chart1,length);
                GlobalBean.page.addChart(chart2,length);
                GlobalBean.page.addChart(chart3,length);
                GlobalBean.page.activateClickEvent(chartName,length);
                break;
        }
	}

    //重新生成直方图
    $(".numberCssA").blur(function() {
        var $this = $(this);
        var val = $this.val();
        if (val && !ComRegex.isNumber(val)) {
            showErrorDialog("", "[" + val + "]不是一个有效的数字,错误");
            $this.val("");
        }
    });


    function histogram(key,grpNum) {
        //画布大小
        var width  = 1000;
        var height = 600;

        //在模态框中设置这个画布
        var svg = d3.select("#svgdiv")
            .append("svg")
            .attr("width",width)
            .attr("height",height);

        //画布周边的空白
        var padding  = {left:30 ,right:30, top:20, bottom:20};

        var point = dataArray[0].point;
        var chart_mean = dataArray[0].target;//中心线
        var dataset = [];
        for(var i = 0 ; i < point.length ; i++){
            dataset.push(parseFloat(point[i].chart_value.toFixed(1)));
        }

        //根据数据分组和组距
        var maxdata = d3.max(dataset);//最大值
        var mindata = d3.min(dataset);//最小值
        var rangedata = maxdata - mindata;//极差
        var datasize = dataset.length;
        var totaldata = 0;
        for(var i = 0;i < dataset.length; i++){
            totaldata += dataset[i];
        }

        var avedata = totaldata / dataset.length;//平均数

        //标准方差
        //var sigma2 = Math.pow(sigma,2);
        var groupN = 1 + 3.322 *(Math.log(dataset.length)/Math.log(10));//组数以10为底
        groupN = Math.ceil(groupN);//向上取整
        if(30 < dataset.length < 50){//样本数量少于50 按6组来算
            groupN = 6;
        }
        //如传入参数
        if(grpNum){
            groupN = grpNum;
        }

        var groupD = Math.ceil(rangedata / groupN); //组距
        var groupV = [];

        groupV.push(mindata - groupD);//最小值前多算一个
        for(var i = 0 ; i <= groupN ; i++){//最大值后多算一个
            groupV.push(mindata + i * groupD);//坐标值
        }
        //算正态分布概率
        //以标准正态分布为准 (7个点) chart_mean
        //var groupZ;
        var ucl1,lcl1;
        if(key.k === 'N'){//设置了
            ucl1 = key.ucl;//3个σ
            lcl1 = key.lcl;
        }else {//没设置
			if(typeof(point[point.length - 1].chart_ucl_fk) !== "undefined"){
                ucl1 = parseFloat(point[point.length - 1].chart_ucl_fk.toFixed(1));
			}
            if(typeof(point[point.length - 1].chart_lcl_fk) !== "undefined") {
                lcl1 = parseFloat(point[point.length - 1].chart_lcl_fk.toFixed(1));
            }
        }
        var x = (chart_mean-lcl1)/3;
        //groupZ =[lcl1-x,lcl1,lcl1+x,lcl1+2*x,chart_mean,ucl1-x,ucl1-2*x,ucl1,ucl1+x]; //x轴坐标
        //标准正态分布9个点
        var groupS = [-4,-3,-2,-1,0,1,2,3,4];
        var pros = [];
        var prototal = [];
        for(var i = 0 ; i < groupS.length ; i++){
            //var pro = 1 / (sigma * Math.sqrt(2 * Math.PI)) * Math.exp(-Math.pow(groupZ[i] - avedata,2) / (2 * sigma2));
            var pro = (1 / Math.sqrt(2 * Math.PI)) * (Math.exp(-Math.pow(groupS[i],2) / 2)); //标准正态分布
            prototal.push(pro);
            pros.push({
                x : groupS[i],//值
                y : pro //parseFloat(pro.toFixed(2)) //密度
            });
        }

        var histogram = d3.layout.histogram()// 直方图的布局
            .range([groupV[1],groupV[groupV.length-2]+groupD])//区间的范围
            .bins((groupV[groupV.length-2]+groupD - groupV[1])/groupD)//分隔数
            .frequency(true);//若值为 true，则统计的是个数；若值为 false，则统计的是概率

        var dataset = histogram(dataset);//转换数据  x:区间的起始位置 dx:区间的宽度 y:落到此区间的数值的数量
        console.log(dataset);
        var xTicks = dataset.map(function(d){
                return d.x;
            }
        );

        //上下控制线  3sigma
        var ucl,lcl;
        if(key.k === 'N'){
            ucl = key.ucl;
            lcl = key.lcl;
        }else {
            if(typeof(point[point.length - 1].chart_ucl_fk) !== "undefined") {
                ucl = parseFloat(point[point.length - 1].chart_ucl_fk.toFixed(1));
            }
            if(typeof(point[point.length - 1].chart_lcl_fk) !== "undefined") {
                lcl = parseFloat(point[point.length - 1].chart_lcl_fk.toFixed(1));
            }
        }

        var n1;
        if(lcl < xTicks[0]){
            n1 = parseInt(((xTicks[0] - lcl) / groupD).toFixed(0)) + 3;
        }else{
            n1 = 3;
        }

        var n2;
        if(ucl < xTicks[xTicks.length-1]){
            n2 = parseInt(((xTicks[xTicks.length-1] - ucl) / groupD ).toFixed(0)) + 3;
        }else{
            n2 = 3;
        }

        for(var i = 0; i < n1;i++){
            xTicks.splice(0, 0, xTicks[0] - groupD);  //头加3组
        }
        for(var i = 0; i < n2 ; i++){
            xTicks.push(xTicks[xTicks.length-1] + groupD);//末尾加3组
        }


        //x轴的比例尺
        var xScale = d3.scale.linear()
            .domain([xTicks[0],xTicks[xTicks.length - 1]])
            .range([0,width - 100]);

        //将X轴实际刻度与标准正态分布曲线X相对应
        var xzScale = d3.scale.linear()
            .domain([-4,4])
            .range([lcl1-x,ucl1+x]);

        //每一个格的px
        var wid = (width - 100)/(xTicks.length);
        var heights = [];
        for(var i = 0 ;i < dataset.length; i++){
            heights.push(dataset[i].y);
        }

        //图上显示用这个 Y轴向下是正方向
        //正态分布最大概率
        var maxPro = Math.max.apply(null,prototal) * 100;
        var m = parseInt(maxPro).toString().split(".");
        if(m[0].length == 1){
            var mp = parseInt(maxPro).toString().slice(0);
            mp =parseInt((parseInt(mp)+1));
        } else if(m[0].length  == 2){//不超过1
            var mp = parseInt(maxPro).toString().slice(0,1);
            mp = parseInt((parseInt(mp)+1).toString()+0);//向上取整
        }else if(m[0].length == 3 ){ //超过1
            var mp = parseInt(maxPro).toString().slice(0,2);
            mp = parseInt((parseInt(mp)+1).toString()+0);//向上取整
        }

        //获得dataset中组数最大的y
        var mprarry = [];
        for(var i = 0; i < dataset.length - 1; i++){
            mprarry.push(dataset[i].y);
        }
        var mpr = d3.max(mprarry);
        var yAxisScale = d3.scale.linear()
            .domain([0,mpr])
            .range([height-50, 0]);

        var yRaxisScale = d3.scale.linear() //显示
            .domain([0,mp/100])
            .range([height-50,0]);

        var yRScale = d3.scale.linear() //实际度量换算
            .domain([0,mp/100])
            .range([0,height-50]);

        //将左y轴的值与右Y轴相对应
        var yrlScale = d3.scale.linear()
            .domain([0,Math.max.apply(null,prototal)])
            .range([0,mpr]);

        //y轴的比例尺（线性比例尺）
        var yScale = d3.scale.linear()
            .domain([0,mpr])
            .range([0,height-50]);

        //定义x轴
        var xAxis = d3.svg.axis().scale(xScale).orient("bottom").tickFormat(d3.format(".1f")).tickValues(xTicks);
        //定义y轴
        var yAxis = d3.svg.axis().scale(yAxisScale).orient("left");
        //定义右边y 轴;
        var yRaxis = d3.svg.axis().scale(yRaxisScale).orient("right");

        //矩形之间的空白
        var rectPadding = 4;

        //添加矩形元素
        var rects = svg.selectAll(".MyRect")
            .data(dataset)
            .enter()
            .append("rect")
            .attr("class","MyRect")
            .attr("x", function(d,i){
                return xScale(d.x) + padding.left;
            } )
            .attr("y",function(d,i){
                return height - yScale(d.y)- 20;
            })
            .attr("width", function (d,i) {
                return  wid - rectPadding;
            } )
            .attr("height", function(d){
                return yScale(d.y);
            })
            .attr("fill", "steelblue");



        //添加文字元素
        var texts =  svg.selectAll("text")
            .data(dataset)
            .enter()
            .append("text")
            .attr("x", function(d,i){
                return xScale(d.x)+ padding.left;
            } )
            .attr("y",function(d,i){
                return height - yScale(d.y)-30;
            })
            .attr("dx", function(d,i){
                return 15;
            })
            .attr("dy", 15)
            .attr("text-anchor", "begin")
            .attr("font-size", 14)
            .attr("fill","black")
            .text(function(d,i){
                return d.y;
            });

        //添加x轴
        svg.append("g")
            .attr("class","axis")
            .attr("transform","translate(" + padding.left + "," + (height - padding.bottom) + ")")
            .call(xAxis);

        //添加y轴
        svg.append("g")
            .attr("class","axis")
            .attr("transform","translate(" + padding.left + "," + padding.top + ")")
            .call(yAxis);

        //添加右边轴
        svg.append("g")
            .attr("class","axis")
            .attr("transform","translate(" + (width-70) + "," + padding.top+ ")")
            .call(yRaxis);

        //画直线和曲线
        var line = d3.svg.line()
            .x(function(d){
                return xScale(xzScale(d.x)) + padding.left;
            })//曲线中x的值
            .y(function(d){
                return height - yScale(yrlScale(d.y))- 20;
            })//曲线中y的值
            .interpolate("cardinal");//把曲线设置光滑 cardinal  linear

		/*   svg.selectAll("circle")
		 .data(pros)
		 .enter()
		 .append("circle")
		 .attr("cx", function(d,i) {
		 var xs = xScale(d.x) +wid;
		 return xScale(d.x) + padding.left;
		 })
		 .attr("cy", function(d) {
		 return height - yRScale(d.y) - 20;
		 })
		 .attr("r",5)
		 .attr("fill","#09F");*/


        var path =  svg.append("path")
            .attr("class","line")
            .attr("d",line(pros))
            .attr('stroke', 'green')
            .attr('stroke-width', 2)
            .attr('fill', 'none');

        //画中心线 15
        var dataC = [{x:chart_mean,y:0},{x:chart_mean,y:mp/100}];
        var lineCenter = d3.svg.line()
            .x(function (d) {
                var xs = xScale(d.x);
                return xScale(d.x)+padding.left;
            })
            .y(function(d){
                return height - yRScale(d.y) - 20;
            })//曲线中y的值
            .interpolate("linear");//把曲线设置光滑 cardinal  linear

        var centerPath = svg.append("path")
            .attr("class","line")
            .attr("d",lineCenter(dataC))
            .attr('stroke', 'green')
            .attr('stroke-dasharray','5,5')
            .attr('stroke-width', 2)
            .attr('fill', 'none');


        var dataUCl = [{x:ucl,y:0},{x:ucl,y:mp/100}];
        var dataLCL = [{x:lcl,y:0},{x:lcl,y:mp/100}];
        var lcl3 = parseFloat((lcl+(chart_mean-lcl)/3).toFixed(1));
        var ucl3 = parseFloat((ucl-(ucl-chart_mean)/3).toFixed(1));//2/3si
        var dataLCL3 = [{x:lcl3,y:0},{x:lcl3,y:mp/100}];
        var dataUCL3 = [{x:ucl3,y:0},{x:ucl3,y:mp/100}];
        var centerPath = svg.append("path")
            .attr("class","line")
            .attr("d",lineCenter(dataUCl))
            .attr('stroke', 'red')
            .attr('stroke-dasharray','5,5')
            .attr('stroke-width', 2)
            .attr('fill', 'none');

        var centerPath = svg.append("path")
            .attr("class","line")
            .attr("d",lineCenter(dataLCL))
            .attr('stroke', 'red')
            .attr('stroke-dasharray','5,5')
            .attr('stroke-width', 2)
            .attr('fill', 'none');

        var centerPath = svg.append("path")
            .attr("class","line")
            .attr("d",lineCenter(dataLCL3))
            .attr('stroke', 'red')
            .attr('stroke-dasharray','5,5')
            .attr('stroke-width', 2)
            .attr('fill', 'none');

        var centerPath = svg.append("path")
            .attr("class","line")
            .attr("d",lineCenter(dataUCL3))
            .attr('stroke', 'red')
            .attr('stroke-dasharray','5,5')
            .attr('stroke-width', 2)
            .attr('fill', 'none');

        //添加σ元素标注
        svg.append("text")
            .attr("x",xScale(lcl)+ padding.left)
            .attr("y", height - yRScale(0)-30)
            .attr("text-anchor", "middle")
            .style("font-size", "16px")
            .style("font-weight","bold")
            .text("-3σ");

        svg.append("text")
            .attr("x",xScale(lcl3)+ padding.left)
            .attr("y", height - yRScale(0)-30)
            .attr("text-anchor", "middle")
            .style("font-size", "16px")
            .style("font-weight","bold")
            .text("-2σ");

        svg.append("text")
            .attr("x",xScale(ucl3)+ padding.left)
            .attr("y", height - yRScale(0)-30)
            .attr("text-anchor", "middle")
            .style("font-size", "16px")
            .style("font-weight","bold")
            .text("2σ");

        svg.append("text")
            .attr("x",xScale(ucl)+ padding.left)
            .attr("y", height - yRScale(0)-30)
            .attr("text-anchor", "middle")
            .style("font-size", "16px")
            .style("font-weight","bold")
            .text("3σ");
    }

	function drawHistogram(){
    	var groupNum = $("#groupNum").val();
		var x = dataArray[0];
		var key = {
        k : 'N',//管制图设置了ucl和lcl
        ucl : dataArray[0].ucl,
        lcl : dataArray[0].lcl
    	};
    	if(typeof(dataArray[0].ucl)=="undefined" && dataArray[0].point.length > 25){
    		key.k = 'UN';
    	}
    	if(document.getElementById("svgdiv").childNodes.length != 0){
        	var list = document.getElementById("svgdiv");
        	list.removeChild(list.childNodes[0]);
    	}
    	if(dataArray[0].point.length >= 30){//样本数至少为30才画直方图
        	histogram(key,parseInt(groupNum));
    	}
        $("#groupNum").val("");
	};

	$("#reBuildBtn").bind('click',drawHistogram);


	DocBean.grids.chartGrid.initFnc();

	DocBean.buttons.clearBtn.ID.click(DocBean.buttons.clearBtn.clickFnc);

	DocBean.buttons.queryBtn.ID.click(DocBean.buttons.queryBtn.clickFnc);

	DocBean.buttons.calcCPKBtn.ID.click(DocBean.buttons.calcCPKBtn.calcCpkFnc);

	DocBean.buttons.refreshBtn.ID.click(DocBean.buttons.refreshBtn.clickFnc);

	//直方图分析按钮
	$("#analysis_btn").click(function () {
        if(dataArray[0].point.length < 30){
            showErrorDialog("","主chart点数不满30个不能生成直方图！");
            return false;
        }
        $("#histogramDialog").modal({
            backdrop : 'static',
            keyboard : false,
            show : false
        });
        $("#histogramDialog").modal("show");
        }
	);

	$("#f11_btn").click(function() {
		var chartDatas = [];
		var summaryDatas = [];
		var rawDatas = [];

		var col_typ, grp_no, chart_no, chart_typ;

		var cusId, mdlId, woId, lotId, pToolId, pOpeId, fromTime, endTime, reportBeginDate, reportBeginTime, reportEndDate, reportEndTime, reportBeginTimestamp, reportEndTimestamp;

		col_typ = GlobalBean.selectedChart.col_typ;
		grp_no = GlobalBean.selectedChart.grp_no;
		chart_no = GlobalBean.selectedChart.chart_no;
		chart_typ = GlobalBean.selectedChart.chart_typ;

		$("#rawDataTbl tr").each(function(i, tr) {
					var raw = [];
					$(tr).find("td,th").each(function(j, td) {
								raw.push($(td).text());
							})

					rawDatas.push(raw);
				});

		$("#chartDataTbl tr").each(function(i, tr) {
					var chartData = [];
					$(tr).find("td,th").each(function(j, td) {
								chartData.push($(td).text());
							})
					chartDatas.push(chartData);
				})

		$("#summaryTbl tr").each(function(i, tr) {
					var summaryData = [];
					$(tr).find("td,th").each(function(j, td) {
								summaryData.push($(td).text());
							})
					summaryDatas.push(summaryData);
				})

		cusId = $("#cusIdSel").val();
		mdlId = BaseFnc.returnSpace($("#mdlIdSel").val());
		woId = $("#woIdSel").val();
		/*lotId = $("#lotIdSel").val();*/
		pToolId = $("#eqptIdSel").val();
		pOpeId = $("#opeIdSel").val();

		// 添加时间的防呆 ， 选日期同时必须选时间
		// reportBeginDate = $("#reportBeginDatepicker input").val();
		// reportBeginTime = $("#reportBeginTimepicker input").val();
		// reportEndDate = $("#reportEndDatepicker input").val()
		// reportEndTime = $("#reportEndTimepicker input").val();
		// if ((!reportBeginDate && reportBeginTime)
		// 		|| (reportBeginDate && !reportBeginTime)) {
		// 	showErrorDialog("", "开始日期和时间必须同时选择");
		// 	return false;
		// }
		// if ((!reportEndDate && reportEndTime)
		// 		|| (reportEndDate && !reportEndTime)) {
		// 	showErrorDialog("", "结束日期和时间必须同时选择");
		// 	return false;
		// }
		// // 时间前面增加checkbox，判定是否增加时间条件
		// if ($("#reportBeginTimestampChk").attr("checked") === "checked") {
		// 	if (!reportBeginDate || !reportBeginTime) {
		// 		showErrorDialog("", "请选择上报开始时间");
		// 		return false;
		// 	}
		// 	reportBeginTimestamp = reportBeginDate + " " + reportBeginTime;
		// }
		// if ($("#reportEndSTimestampChk").attr("checked") === "checked") {
		// 	if (!reportEndDate || !reportEndTime) {
		// 		showErrorDialog("", "请选择上报结束时间")
		// 		return false;
		// 	}
		// 	reportEndTimestamp = reportEndDate + " " + reportEndTime;
		// }

        var reportBeginTimestamp = $.trim($("#reportBeginDate").val());
        var reportEndTimestamp   = $.trim($("#reportEndDate").val());

        if((!reportBeginTimestamp && reportEndTimestamp) || (reportBeginTimestamp && !reportEndTimestamp)){
            showErrorDialog("","上报开始时间和上报结束时间必须同时选择！");
            return false;
        }

        if(reportBeginTimestamp && reportEndTimestamp){
            var reportDateStart  = reportBeginTimestamp.replace("-","/");//替换字符，变成标准格式
            var reportDateEnd  = reportEndTimestamp.replace("-","/");//替换字符，变成标准格式
            var d1 = new Date(Date.parse(reportDateStart));
            var d2 = new Date(Date.parse(reportDateEnd));
            if(d1>d2){
                showErrorDialog("","上报开始时间 不能大于 上报结束时间！");
                return false;
            }
        }

		// console.info(reportBeginTimestamp + ", " + reportEndTimestamp);

		var inObj = {
			col_typ_fk : GlobalBean.selectedChart.col_typ,
			grp_no_fk : GlobalBean.selectedChart.grp_no,
			chart_no : GlobalBean.selectedChart.chart_no
		};

		// fix for export excel's inTrx missing chart_typ;
		inObj.chart_typ = GlobalBean.selectedChart.chart_typ;

		if (cusId) {
			inObj.cus_id = cusId;
		}
		if (mdlId) {
			inObj.mdl_id = mdlId;
		}
		if (woId) {
			inObj.wo_id = woId;
		}
		/*if (lotId) {
			inObj.lot_id = lotId;
		}*/
		if (pToolId) {
			inObj.p_tool_id = pToolId;
		}
		if (pOpeId) {
			inObj.p_ope_id = pOpeId;
		}
		if (reportBeginTimestamp) {
			inObj.input_timestamp_from = reportBeginTimestamp;
		}
		if (reportEndTimestamp) {
			inObj.input_timestamp_to = reportEndTimestamp;
		}

		var str = '<form id= "exportExcelForm" style="position:display;z-index:-1122;" method="post" action="exportChartData.do">';
		str = str + "<input id='rawDataTxt' type='hidden' name = 'rawData' / >";
		str = str
				+ "<input id='chartDataTxt' type='hidden'  name = 'chartData'/>";
		str = str
				+ "<input id='summaryDataTxt' type='hidden'  name = 'summaryData' />";
		str = str + "<input id='colTypTxt' type='hidden'  name = 'col_typ' />";
		str = str + "<input id='grpNoTxt' type='hidden'  name = 'grp_no' />";
		str = str
				+ "<input id='chartNoTxt' type='hidden'  name = 'chart_no' />";
		str = str
				+ "<input id='chartTypTxt'ype='hidden'  name = 'chart_typ' />";
		str = str + "<input id='cusIdTxt' type='hidden'  name = 'cus_id' />";
		str = str + "<input id='mdlIdTxt' type='hidden'  name = 'mdl_id' />";
		str = str + "<input id='woIdTxt' type='hidden'  name = 'wo_id' />";
		/*str = str + "<input id='lotIdTxt' type='hidden'  name = 'lot_id' />";*/
		str = str + "<input id='pToolId' type='hidden'  name = 'p_tool_id' />";
		str = str + "<input id='pOpeId' type='hidden'  name = 'p_ope_id' />";
		str = str
				+ "<input id='inputTimestampFromTxt' type='hidden'  name = 'input_timestamp_from' />";
		str = str
				+ "<input id='inputTimestampToTxt' type='hidden'  name = 'input_timestamp_to' />";
		str = str + "<input id='limitFlgTxt' type='hidden' name = 'limitFlg'  value='N' / >";		
		str = str + "</form>";

		if ($("#exportExcelForm").length > 0) {
			$("#exportExcelForm").remove();
		}
		$(str).appendTo("body");
		$("#rawDataTxt").val(JSON.stringify(rawDatas));
		$("#chartDataTxt").val(JSON.stringify(chartDatas));
		$("#summaryDataTxt").val(JSON.stringify(summaryDatas));
		if($("#rawDataTxt").val().length == 2
			&& $("#chartDataTxt").val().length == 2
			&& $("#summaryDataTxt").val().length == 2){
            $("#exportExcelForm").remove();
            showErrorDialog("", "没有数据可以导出，请重新选择！");
            return false;
		}

		$("#colTypTxt").val(GlobalBean.selectedChart.col_typ)
		$("#grpNoTxt").val(GlobalBean.selectedChart.grp_no)
		$("#chartNoTxt").val(GlobalBean.selectedChart.chart_no)
		$("#chartTypTxt").val(GlobalBean.selectedChart.chart_typ)
		$("#cusIdTxt").val(cusId);
		$("#mdlIdTxt").val(mdlId);
		$("#woIdTxt").val(woId);
		/*$("#lotIdTxt").val(lotId);*/
		$("#pToolId").val(pToolId);
		$("#pOpeId").val(pOpeId);
		$("#inputTimestampFromTxt").val(reportBeginTimestamp);
		$("inputTimestampToTxt").val(reportEndTimestamp);

		$("#exportExcelForm").submit();
			// var col_typ, grp_no, chart_no, chart_typ;
			//
			// col_typ = GlobalBean.selectedChart.col_typ;
			// grp_no = GlobalBean.selectedChart.grp_no;
			// chart_no = GlobalBean.selectedChart.chart_no;
			// chart_typ = GlobalBean.selectedChart.chart_typ;
        $("#exportExcelForm").remove();
	});
	var BaseFnc = {
		replaceSpace : function(str) {
			if (!str) {
				return str;
			}
			return str.replace(/[ ]/g, "@");
		},
		returnSpace : function(str) {
			if (!str) {
				return str;
			}
			return str.replace(/[@]/g, " ");
		}
	};

	$("#reportBeginDatepicker").hide();
	$("#reportBeginTimepicker").hide();
	$("#reportEndDatepicker").hide();
	$("#reportEndTimepicker").hide();

	$("#reportBeginTimestampChk").click(function() {
				if ($(this).attr("checked") == "checked") {
					$("#reportBeginDatepicker").show();
					$("#reportBeginTimepicker").show();
				} else {
					$("#reportBeginDatepicker").hide();
					$("#reportBeginTimepicker").hide();
				}
			})
	$("#reportEndSTimestampChk").click(function() {
				if ($(this).attr("checked") == "checked") {
					$("#reportEndDatepicker").show();
					$("#reportEndTimepicker").show();
				} else {
					$("#reportEndDatepicker").hide();
					$("#reportEndTimepicker").hide();
				}
			})

	function filterChartFnc(cusId, mdlId, woId, fabIdFk,lineIdFk,pToolId, pOpeId,shiftId,boatNumber, reportBeginTimestamp, reportEndTimestamp,first) {
		/*var inObj = {
			col_typ_fk : GlobalBean.selectedChart.col_typ,
			grp_no_fk : GlobalBean.selectedChart.grp_no,
			chart_no : GlobalBean.selectedChart.chart_no
		};*/
		var inObj={};

		DocBean.buttons.clearBtn.clickFnc();
		if (cusId) {
			inObj.cus_id = cusId;
		}
		if (mdlId) {
			inObj.mdl_id = mdlId;
		}
		if (woId) {
			inObj.wo_id = woId;
		}
		if (pToolId) {
			inObj.p_tool_id = pToolId;
		}
		if (pOpeId) {
			inObj.p_ope_id = pOpeId;
		}
		if(fabIdFk){
			inObj.fab_id_fk = fabIdFk;
		}
        if(lineIdFk){
            inObj.line_id_fk = lineIdFk;
        }

        if(shiftId){
        	inObj.shift_id_fk = shiftId;
		}

		if(boatNumber){
        	inObj.boat_number = boatNumber;
		}

		if (reportBeginTimestamp) {
			inObj.input_timestamp_from = reportBeginTimestamp;
		}
		if (reportEndTimestamp) {
			inObj.input_timestamp_to = reportEndTimestamp;
		}
		DocBean.buttons.clearBtn.clickFnc();
		// fix for export excel's inTrx missing chart_typ;
		inObj.chart_typ = GlobalBean.selectedChart.chart_typ;
        var length = GlobalBean.chartCollenction.length;
        for(var i = 0; i < length; i++) {
            //新建N个canvas
            var canvas = document.createElement('canvas');
            //按顺序设置ID
            var chartName = "chart" + i;
            canvas.setAttribute("id", chartName);
            document.getElementById("canvastotal").appendChild(canvas);
            inObj.col_typ_fk = GlobalBean.chartCollenction[i].col_typ_fk;
            inObj.grp_no_fk = GlobalBean.chartCollenction[i].grp_no_fk;
            inObj.chart_no = GlobalBean.chartCollenction[i].chart_no;
           /* showChart({
                col_typ_fk: GlobalBean.chartCollenction[i].col_typ_fk,
                grp_no_fk: GlobalBean.chartCollenction[i].grp_no_fk,
                chart_no: GlobalBean.chartCollenction[i].chart_no
            }, true, true, length, chartName);*/
            showChart(inObj, true, first,length,chartName);
        }

	}

    $("#f2_filter_btn").bind('click',filter);

    function filter(first){
        var cusId, mdlId, woId, lotId, pToolId, pOpeId, fromTime, endTime, reportBeginDate, reportBeginTime, reportEndDate, reportEndTime, reportBeginTimestamp, reportEndTimestamp;

        cusId = $("#cusIdSel").val();
        mdlId = BaseFnc.returnSpace($("#mdlIdSel").val());
        woId = $("#woIdSel").val();
        //lotId = $("#lotIdSel").val();
        pToolId = $("#eqptIdSel").val();
        pOpeId = $("#opeIdSel").val();
        var shiftId = $("#shiftIdSel").val();
        var boatNumber = $("#boatNumber").val();
		var fabIdFk = $("#fabIdSel").val();
		var lineIdFk = $("#lineIdSel").val();
        // 当没有管制图显示时，不能进行筛选
		/*  if (GlobalBean.displayChartCount <= 0) {
		 showErrorDialog("", "当前没有可以被筛选的管制图");
		 return false;
		 }*/

        // 添加时间的防呆 ， 选日期同时必须选时间
        // reportBeginDate = $("#reportBeginDatepicker input").val();
        // reportBeginTime = $("#reportBeginTimepicker input").val();
        // reportEndDate = $("#reportEndDatepicker input").val()
        // reportEndTime = $("#reportEndTimepicker input").val();
        // if ((!reportBeginDate && reportBeginTime)
        //     || (reportBeginDate && !reportBeginTime)) {
        //     showErrorDialog("", "开始日期和时间必须同时选择");
        //     return false;
        // }
        // if ((!reportEndDate && reportEndTime)
        //     || (reportEndDate && !reportEndTime)) {
        //     showErrorDialog("", "结束日期和时间必须同时选择");
        //     return false;
        // }
        // // 时间前面增加checkbox，判定是否增加时间条件
        // if ($("#reportBeginTimestampChk").attr("checked") === "checked") {
        //     if (!reportBeginDate || !reportBeginTime) {
        //         showErrorDialog("", "请选择上报开始时间");
        //         return false;
        //     }
        //     reportBeginTimestamp = reportBeginDate + " " + reportBeginTime;
        // }
        // if ($("#reportEndSTimestampChk").attr("checked") === "checked") {
        //     if (!reportEndDate || !reportEndTime) {
        //         showErrorDialog("", "请选择上报结束时间")
        //         return false;
        //     }
        //     reportEndTimestamp = reportEndDate + " " + reportEndTime;
        // }
        var reportBeginTimestamp = $.trim($("#reportBeginDate").val());
        var reportEndTimestamp   = $.trim($("#reportEndDate").val());

        if((!reportBeginTimestamp && reportEndTimestamp) || (reportBeginTimestamp && !reportEndTimestamp)){
            showErrorDialog("","上报开始时间和上报结束时间必须同时选择！");
            return false;
        }

        if(reportBeginTimestamp && reportEndTimestamp){
            var reportDateStart  = reportBeginTimestamp.replace("-","/");//替换字符，变成标准格式
            var reportDateEnd  = reportEndTimestamp.replace("-","/");//替换字符，变成标准格式
            var d1 = new Date(Date.parse(reportDateStart));
            var d2 = new Date(Date.parse(reportDateEnd));
            if(d1>d2){
                showErrorDialog("","上报开始时间 不能大于 上报结束时间！");
                return false;
            }
        }

        if(reportBeginTimestamp && reportEndTimestamp){
            first = 'N';
        }
        first = 'N';

        filterChartFnc(cusId, mdlId, woId,fabIdFk,lineIdFk, pToolId, pOpeId,shiftId ,boatNumber,reportBeginTimestamp, reportEndTimestamp,first);
    };

	function iniDateTimePicker() {
		// var datepickerBeginDate, datepickerBeginTime, datepickerEndDate, datepickerEndTime;
		// $("#reportBeginDatepicker,#reportEndDatepicker,#filterChartDialog_reportBeginDatepicker,#filterChartDialog_reportEndDatepicker")
		// 		.datetimepicker({
		// 					language : 'zh-CN',
		// 					pickTime : false,
		// 		            weekStart: 1,
		// 		            autoclose: true,
		// 		            orientation:'right',
		// 				});
		// $("#reportBeginTimepicker,#reportEndTimepicker,#filterChartDialog_reportBeginTimepicker,#filterChartDialog_reportEndTimepicker")
		// 		.datetimepicker({
		// 					language : 'zh-CN',
		// 					pickDate : false
		// 				});
		// datepickerBeginDate = $("#reportBeginDatepicker")
		// 		.data("datetimepicker");
		// datepickerBeginDate.setLocalDate(datepickerBeginDate.getLocalDate());
        //
		// datepickerBeginTime = $("#reportBeginTimepicker")
		// 		.data("datetimepicker");
		// datepickerBeginTime.setLocalDate(new Date());
        //
		// datepickerEndDate = $("#reportEndDatepicker").data("datetimepicker");
		// datepickerEndDate.setLocalDate(datepickerEndDate.getLocalDate());
        //
		// datepickerEndTime = $("#reportEndTimepicker").data("datetimepicker");
		// datepickerEndTime.setLocalDate(new Date());

        laydate.render({
            elem: '#reportBeginDate',
            type: 'datetime'
        });
        laydate.render({
            elem: '#reportEndDate',
            type: 'datetime'
        });

	}
	iniDateTimePicker();

	function fillChartDataGrdBySlaveChartData(pointArr) {
		var i, point, row3, pointCnt;
		var str = "<tr><td>子图点值</td>";

		pointCnt = pointArr.length;

		for (i = 0; i < pointCnt; i++) {
			point = pointArr[i];
			str += "<td>" + point.value.toFixed(3) + "</td>";
		}

		str += "</tr>";
		$(str).appendTo("#chartDataTbl tbody");
	}
	function fillChatDataGrd(pointArr) {
		var i, j, pointCnt, columns, point, rawArr, obj, raw, row1, row2, row3, rawValue, str;
		pointCnt = pointArr.length;

		var theadStr = '';
		var row1Str = "<td>原始值求和</td>", row2Str = "<td  style='width:80px'>主图点值</td>", row3Str = "<td style='width:100px'>子图点值</td>";
		for (i = 0; i < pointCnt; i++) {
			theadStr += '<th>' + (i + 1) + '</th>'
			point = pointArr[i];
			rawArr = point.rawData;
			if (rawArr) {
				rawValue = 0;
				for (j = 0; j < rawArr.length; j++) {
					raw = rawArr[j];
					rawValue = rawValue + raw.prd_raw_value;
				}
				row1Str += "<td>" + rawValue.toFixed(3) + "</td>";

			}
			row2Str += "<td>" + point.value.toFixed(3) + "</td>"
		}
		// str = '<div id="chartDataDiv" class="span12">
		str = '<fieldset>管制图数据</fieldset>';
		str += ' <table  id="chartDataTbl" class="table table-bordered table-condensed" ><thead><th><div style="width:100px"></div></th>'
				+ theadStr + '</thead>';
		str += "<tbody><tr>" + row1Str + "</tr>";
		str += "<tr>" + row2Str + "</tr></tbody></table>";
		$("#chartDataDiv").empty();
		// if ($("#chartDataDiv").length > 0) {
		// $("#chartDataDiv").remove();
		// }
		$(str).appendTo("#chartDataDiv");
	}

	function clearRawDataGrd() {
		$("#rawDataDiv").empty();
	}
	function fillRawDataGrd(pointArr, usl, lsl) {
		var i, columns, rows = [], rawArr, row, point, str, pointCnt = pointArr.length;
		var str, headStr, bodyStr = "", rowStr;

		headStr = buildRawDataHeadStr(pointCnt);
		if (!headStr) {
			return false
		}

		bodyStr = buildRawDataRowStr(pointArr, usl, lsl);
		if (!bodyStr) {
			return false;
		}
		str = '<fieldset>原始数据</fieldset> ';
		str += '<table id="rawDataTbl"  class="table table-bordered table-condensed"><thead>';
		str += headStr + '</thead>';
		str += '<tbody>' + bodyStr + '</tbody>';
		str += '</table>';
		if ($("#rawDataTbl").length > 0) {
			$("#rawDataTbl").remove();
		}
		$("#rawDataDiv").append(str);
		// console.info(str);
		// console.info($("#rawDataDiv").html());

		// DocBean.grids.rawDataGrd.initFnc(columns, rows);

	}

	// 将一组rawData组成一行 并返回
	function buildRawDataRowStr(pointArr, usl, lsl) {
		var str = "", raw, i, j, pointCnt = pointArr.length, rawDataCnt, maxRawDataCnt;

		var rawDataCnt = 0;
		maxRawDataCnt = 0;
		if (pointCnt <= 0) {
			return false;
		}

		for (i = 0; i < pointArr.length; i++) {
			if (pointArr[i].rawData) {
				rawDataCnt = pointArr[i].rawData.length;
				if (rawDataCnt > maxRawDataCnt) {
					maxRawDataCnt = rawDataCnt;
				}
			}
		}

		if (maxRawDataCnt <= 0) {
			return false;
		}

		// add tr : prd_seq_id
		str = str + "<tr><td>玻璃ID</td>";
		for (i = 0; i < pointCnt; i++) {
			var point = pointArr[i];
			if (isOOS(point.value, point.chart_typ_fk, usl, lsl)) {
				str += "<td style ='color:red' >" + point.glassId + "</td>";
			} else {
				str += "<td>" + point.glassId + "</td>";
			}

		}
		str = str + "</tr>";

		for (i = 0; i < maxRawDataCnt; i++) {
			str = str + "<tr><td>" + (i + 1) + "</td>";
			for (j = 0; j < pointCnt; j++) {
				var point = pointArr[j];
				console.info(point);
				var rawData = point ? point.rawData : null;
				console.info(rawData);

				raw = (rawData && $.isArray(rawData) && rawData.length > i - 1)
						? rawData[i]
						: null;

				if (raw) {
					if (isOOS(raw.prd_raw_value, pointArr[j].chart_typ_fk, usl,
							lsl)) {
						str += "<td style ='color:red'>" + raw.prd_raw_value
								+ "</td>";
					} else {
						str += "<td>" + raw.prd_raw_value + "</td>";
					}
				} else {
					str += "<td></td>";
				}
			}
			str += "</tr>";
		}

		return str;
	}

	function buildRawDataHeadStr(pointCnt) {
		var str = "<thead><th></th>";
		if (pointCnt <= 0) {
			return null;
		}
		for (i = 0; i < pointCnt; i++) {
			str += "<th>" + (i + 1) + "</th>";
		}
		str += "</thead>";
		return str;
	}

	function fillSummaryDataGrd(summaryObj) {

		var str, bodyStr = "";
		var ca, cp, cpu, cpl, cpk, pp, ppk, mainTarget, grade, totalSampleCnt, totalGroupCnt, rawDataCnt;
		var totalSampleValue, totalMainChartValue, totalSlaveValue, averageMainChartValue, averageSlaveChartValue;
		var sigma, mainUsl, mainLsl, mainUcl, mainLcl, slaveUcl, slaveLcl;
		var mainPoint, i, j, raw, slavePoint;
		var mainChartSetting = summaryObj.mainChartSetting, slaveChartSetting = summaryObj.slaveChartSetting;
		var mainChartPointArr = summaryObj.mainChartPointArr, slaveChartPointArr = summaryObj.slaveChartPointArr;
		// var pointCnt = mainChartPointArr.length, slavePointCnt =
		// slaveChartPointArr.length;
		var pointCnt = mainChartPointArr.length, slavePointCnt;

		if (mainChartSetting.chart_typ_fk === "40"
				|| mainChartSetting.chart_typ_fk === "50"
				|| mainChartSetting.chart_typ_fk === "60"
            	|| mainChartSetting.chart_typ_fk === "10" ) {
			slavePointCnt = 0;
			if (!mainChartSetting || !mainChartPointArr) {
				return false;
			}
			slaveUcl = 0;
			slaveLcl = 0;

		} else {
			if (!mainChartSetting || !slaveChartSetting || !mainChartPointArr
					|| !slaveChartPointArr) {
				return false;
			}
            slavePointCnt = slaveChartPointArr.length;
			slaveUcl = slaveChartSetting.chart_ucl;
			slaveLcl = slaveChartSetting.chart_lcl;
		}

		// 总样本数
		totalSampleCnt = pointCnt;

		mainUsl = mainChartSetting.chart_usl;
		mainLsl = mainChartSetting.chart_lsl;
		if(typeof (mainChartSetting.chart_ucl) == "undefined"){
			if(mainChartPointArr.length > 25 && mainChartSetting.chart_typ_fk =='01'){
                mainUcl =  mainChartPointArr[mainChartPointArr.length-1].chart_ucl_fk.toFixed(2);
			}
			/*if(typeof (mainChartPointArr[mainChartPointArr.length-1].chart_ucl_fk) !== "undefined"){

			}*/
		}else{
            mainUcl = mainChartSetting.chart_ucl;
		}

		if(typeof (mainChartSetting.chart_lcl) == "undefined"){
            if(mainChartPointArr.length > 25 && mainChartSetting.chart_typ_fk =='01'){
                mainLcl = mainChartPointArr[mainChartPointArr.length-1].chart_lcl_fk.toFixed(2);
            }
			/*if(typeof (mainChartPointArr[mainChartPointArr.length-1].chart_lcl_fk) !== "undefined"){

			}*/
		}else{
            mainLcl = mainChartSetting.chart_lcl;
		}

		mainTarget = mainChartSetting.chart_target;

		totalSampleValue = 0;
		totalMainChartValue = 0;
		totalSlaveValue = 0;

		for (i = 0; i < pointCnt; i++) {
			mainPoint = mainChartPointArr[i];
			var chartTyp = mainChartSetting.chart_typ_fk;

			if (chartTyp === "01" || chartTyp === "30") {

				rawArr = mainPoint.rawData;
				// 组内数
				rawDataCnt = $.isArray(rawArr) ? rawArr.length : 0;
				if (rawArr && rawDataCnt > 0) {
					for (j = 0; j < rawDataCnt; j++) {
						raw = rawArr[j];

						// 总主图值：所有mean点加总
						totalMainChartValue += raw.prd_raw_value;
					}
				}

			}

			// 总样本值
			totalSampleValue += mainPoint.value;

		}

		if (slavePointCnt != 0) {
			// 总子图值 : 子图所有点加总
			for (i = 0; i < slaveChartPointArr.length; i++) {
				slavePoint = slaveChartPointArr[i];
				totalSlaveValue += slavePoint.value;
			}

		} else {
			totalSlaveValue = 0;
		}
		// 总组数 = 总样本数 * 组内数
		totalGroupCnt = totalSampleCnt * rawDataCnt;

		// 主图均值 = 总样本值/总样本数
		averageMainChartValue = totalSampleValue / totalSampleCnt;

		// 子图均值 ＝ 总子图值/样本总数
		averageSlaveChartValue = totalSlaveValue / totalSampleCnt;

		// ca = (实际均值 - 中心值) / (t/2) --- t = (usl - lsl)
		var t = mainUsl - mainLsl;
		ca = Math.abs((averageMainChartValue - mainTarget) / (t / 2));
		//单边
		if(mainUsl == null || mainLsl == null){
			ca = 0;
		}

		// sigma 标准差
		var avgSum = 0;
		var mean = averageMainChartValue;
		for (i = 0; i < pointCnt; i++) {
			mainPoint = mainChartPointArr[i];
			avgSum += (mainPoint.value - mean) * (mainPoint.value - mean);
		}
		sigma = Math.sqrt(avgSum / (pointCnt - 1));
		cp = t / (6 * sigma);
		//单边
		if(mainUsl == null && mainLsl != null){
			cp = (mean - mainLsl)/(3 * sigma);
		}else if(mainUsl != null && mainLsl == null){
            cp = (mainUsl - mean)/(3 * sigma);
		}

		cpl = (mean - mainLsl) / (6 * sigma);
		cpu = (mainUsl - mean) / (6 * sigma);

		// cpk = cpl > cpu ? cpu : cpl;
		cpk = (1-Math.abs(ca)) * cp;
		//单边
		if(mainUsl == null || mainLsl == null){
			cpk = cp;
		}

		// 计算ppk
		// 计算 sigma_ppk
		var sigma_ppk;
		if (mainChartSetting.chart_typ_fk == "01") {
			var tmpSumSum_ppk = 0;
			for (i = 0; i < pointCnt; i++) {
				point = mainChartPointArr[i];
				var tmpSum_ppk = 0;
				if (point.rawData && $.isArray(point.rawData)) {

					for (j = 0; j < point.rawData.length; j++) {
						raw = point.rawData[j];
						var rawValue = raw.prd_raw_value;
						tmpSum_ppk = tmpSum_ppk
								+ Math.pow((rawValue - mean), 2);
					}

					tmpSumSum_ppk = tmpSumSum_ppk + tmpSum_ppk;
				}
			}
			sigma_ppk = Math.sqrt(tmpSumSum_ppk / (pointCnt * rawDataCnt - 1));

			// 计算 pp
			if (mainUsl != null && mainLsl != null) {
				pp = (mainUsl - mainLsl) / (sigma_ppk * 6);
			} else if (mainUsl != null && mainLsl == null) {
				pp = (mainUsl - mean) / (sigma_ppk * 3);
			} else if (mainUsl == null && mainLsl != null) {
				pp = (mean - mainLsl) / (sigma_ppk * 3);
			}
			// 计算 ppk
			if (mainUsl != null && mainLsl != null) {
				ppk = (1 - Math.abs(ca)) * pp;
			} else {
				ppk = pp;
			}

		} else {
			sigma_ppk = sigma;
			ppk = cpk;
		}

		if (cpk >= 1.67) {
			grade = "A+";
		} else if (cpk >= 1.33) {
			grade = "A";
		} else if (cpk >= 1.00) {
			grade = "B";
		} else if (cpk >= 0.67) {
			grade = "C";
		} else {
			grade = "D";
		}

		bodyStr = "<tr>" + wrapByTd(ca) + wrapByTd(cp) + wrapByTd(cpu)
				+ wrapByTd(cpl) + wrapByTd(cpk) + wrapByTd(pp) + wrapByTd(ppk);
		bodyStr += wrapByTd(grade, false) + wrapByTd(totalSampleCnt, false)
				+ wrapByTd(totalGroupCnt, false) + wrapByTd(rawDataCnt, false);
		bodyStr += wrapByTd(totalSampleValue) + wrapByTd(totalMainChartValue)
				+ wrapByTd(totalSlaveValue);
		bodyStr += wrapByTd(averageMainChartValue)
				+ wrapByTd(averageSlaveChartValue);
		bodyStr += wrapByTd(sigma) + wrapByTd(mainUsl) + wrapByTd(mainLsl)
				+ wrapByTd(mainUcl) + wrapByTd(mainLcl) + wrapByTd(slaveUcl)
				+ wrapByTd(slaveLcl);
		bodyStr += "</tr>";

		str = '<div id="sumaryDiv" class="col-lg-12 col-md-12 col-sm-12" >';
		str += '<fieldset>汇总数据</fieldset>';
		str += '<table id="summaryTbl" class="table table-bordered table-condensed">';
		str += '<thead><th>CA</th><th>CP</th><th>CPU</th><th>CPL</th><th>CPK</th>';
		str += '<th>PP</th><th>PPK</th><th>GRADE</th>';
		str += '<th>总样本数</th><th>总组数</th><th>组内数</th>';
		str += '<th>总样本值</th><th>总主图值</th><th>总子图值</th>';
		str += '<th>主图均值</th><th>子图均值</th>';
		str += '<th>标准差</th><th>主USL</th><th>主LSL</th>';
		str += '<th>主UCL</th><th>主LCL</th><th>子UCL</th><th>子LCL</th></thead>';
		str += '<tbody>'
		str += bodyStr + '</tbody></table></div>';
		if ($("#sumaryDiv").length > 0) {
			$("#sumaryDiv").remove();
		}
        //$("#sumaryDiv").append(str);
		$(str).appendTo("body");
	}

	function wrapByTd(dbl, formatFlg) {
		if (typeof(formatFlg) !== "undefined" && !formatFlg) {
			return "<td>" + dbl + "</td>";
		}
		return "<td>" + formatDouble(dbl) + "</td>";
	}

	function wrapAndFixedByTd(dbl, formatFlg) {
		if (typeof(formatFlg) !== "undefined" && !formatFlg) {
			return "<td>" + dbl + "</td>";
		}
		return "<td>" + formatDouble(dbl) + "</td>";
	}

	function formatDouble(dbl) {
		var strDbl = dbl + "";
		var index = strDbl.indexOf(".");
		if (index === -1) {
			return strDbl + ".000";
		}
		var strRight = strDbl.substr(index + 1);
		var strLeft = strDbl.substr(0, index);
		if (strRight.length > 3) {
			return strDbl.substr(0, index + 4);
		} else {
			return strLeft + "." + ComL2S(strRight, 3, "0")
		}
	}
	function ComL2S(data1, length, data2) {
		if (length <= 0) {
			return null;
		}
		var str = data1.toString();
		if (data1.length > length) {
			return null;
		}
		var size = str.length;
		var chazhi = length - size;
		for (var i = 0; i < chazhi; i++) {
			str = str + data2;
		}
		return str;
	}
	function isOOS(pointValue, chartTyp, usl, lsl) {

		return isMainChart(chartTyp)
				&& ((usl != null && pointValue > usl) || (lsl != null && pointValue < lsl));
	}
	function isBreakRule(ruleRlt, chartTyp) {

		if (isMainChart() && ruleRlt) {
			return ruleRlt.indexOf("Y") == -1 ? false : true;
		}
		return false;
	}
	function isMainChart(chartTyp) {
		return chartTyp == "01" || chartTyp == "10" || chartTyp == '30'
				|| chartTyp == '40' || chartTyp == '50' || chartTyp == '60';
	}

	function sendTxAddSelect(trxId, actionFlg, iary, $selectDom, val, text) {
		var inObj, outObj, tblCnt, oary, i;
		inObj = {
			trx_id : trxId,
			action_flg : actionFlg,
			iary : [iary]
		};
		outObj = comTrxSubSendPostJson(inObj);
		if (outObj.rtn_code === "0000000") {
			tblCnt = outObj.tbl_cnt;
			$selectDom.empty();
			for (i = 0; i < tblCnt; i++) {
				oary = outObj.oary;
				oary = $.isArray(oary) ? oary : [oary];
				SelectDom.addSelect($selectDom, oary[i][val], oary[i][text]);
			}
		}
	}

	var FilterDialog = {
		setCusId : function() {

			var chartDataCondition = GlobalBean.chartDataCondition;
			var i, cusIds = chartDataCondition.cusIdSet;

			if (chartDataCondition) {
				SelectDom.initWithSpace($("#filterChartDialog_cusIdSel"));

				for (i = 0; i < cusIds.length; i++) {
					SelectDom.addSelect($("#filterChartDialog_cusIdSel"),
							cusIds[i],cusIds[i]);
				}
			}
		},

		setMdlId : function(cusId) {
			var chartDataCondition = GlobalBean.chartDataCondition;
			var i, mdlOary;
			if (chartDataCondition) {

				mdlOary = cusId
						? chartDataCondition.cusMdlMap[cusId]
						: chartDataCondition.mdlIdSet;

				SelectDom.initWithSpace($("#filterChartDialog_mdlIdSel"));

				for (i = 0; i < mdlOary.length; i++) {
					SelectDom.addSelect($("#filterChartDialog_mdlIdSel"),
							BaseFnc.replaceSpace(mdlOary[i]), mdlOary[i]);
				}
			}
		},
		setWoId : function(mdlId) {
			var chartDataCondition = GlobalBean.chartDataCondition;
			var i, woOary;
			mdlId = BaseFnc.returnSpace(mdlId);

			if (chartDataCondition) {

				woOary = mdlId
						? chartDataCondition.mdlWoMap[mdlId]
						: chartDataCondition.woIdSet;

				SelectDom.initWithSpace($("#filterChartDialog_woIdSel"));

				for (i = 0; i < woOary.length; i++) {
					SelectDom.addSelect($("#filterChartDialog_woIdSel"),
							woOary[i]);
				}

			}

		},
		setLotId : function(woId) {
			var chartDataCondition = GlobalBean.chartDataCondition;
			var i, lotOary;

			lotOary = woId ? chartDataCondition.woLotMap[woId]: chartDataCondition.woIdSet;

			SelectDom.initWithSpace($("#filterChartDialog_lotIdSel"));

			for (i = 0; i < lotOary.length; i++) {
				SelectDom.addSelect($("#filterChartDialog_lotIdSel"),
						lotOary[i]);
			}
		},
		setOpeId : function() {
			var chartDataCondition = GlobalBean.chartDataCondition;
			var i, opeOary;

			opeOary = chartDataCondition.opeIdSet;

			SelectDom.initWithSpace($("#filterChartDialog_opeIdSel"));

			for (i = 0; i < opeOary.length; i++) {
				SelectDom.addSelect($("#filterChartDialog_opeIdSel"),
						opeOary[i]);
			}

		},
		setToolId : function(opeId) {
			var chartDataCondition = GlobalBean.chartDataCondition;
			var i, toolOary;

			toolOary = opeId
					? chartDataCondition.opeToolMap[opeId]
					: chartDataCondition.toolIdSet;

			SelectDom.initWithSpace($("#filterChartDialog_toolIdSel"));

			for (i = 0; i < toolOary.length; i++) {
				SelectDom.addSelect($("#filterChartDialog_toolIdSel"),
						toolOary[i]);
			}
		}
	}

	$("#filterChartDialog").on("change", "#filterChartDialog_cusIdSel",
			function() {
				FilterDialog.setMdlId($("#filterChartDialog_cusIdSel").val());
				// FilterDialog.setWoId($("#filterChartDialog_mdlIdSel").val());
		})
	$("#filterChartDialog").on("change", "#filterChartDialog_mdlIdSel",
			function() {
				FilterDialog.setWoId($("#filterChartDialog_mdlIdSel").val());
			})

	/*$("#filterChartDialog").on("change", "#filterChartDialog_woIdSel",
			function() {
				FilterDialog.setLotId($("#filterChartDialog_woIdSel").val());
			})*/

	$("#filterChartDialog").on("change", "#filterChartDialog_opeIdSel",
			function() {
				FilterDialog.setToolId($("#filterChartDialog_opeIdSel").val(),
						"00000");
			})
	$("#filterChartDialog").on("click", "#filterChartDialog_queryBtn",
			function() {
				var cusId, mdlId, woId, lotId, pToolId, pOpeId, fromTime, endTime, reportBeginDate, reportBeginTime, reportEndDate, reportEndTime, reportBeginTimestamp, reportEndTimestamp;

				cusId = $("#filterChartDialog_cusIdSel").val();
				mdlId = BaseFnc.returnSpace($("#filterChartDialog_mdlIdSel")
						.val());
				woId = $("#filterChartDialog_woIdSel").val();
				/*lotId = $("#filterChartDialog_lotIdSel").val();*/
				pToolId = $("#filterChartDialog_toolIdSel").val();
				pOpeId = $("#filterChartDialog_opeIdSel").val();
				var shiftId = $("#shiftIdSel").val();
				var boatNumber = $("#boatNumber").val();
				// 当没有管制图显示时，不能进行筛选
				if (GlobalBean.displayChartCount <= 0) {
					showErrorDialog("", "当前没有可以被筛选的管制图");
					return false;
				}

                var reportBeginTimestamp = $.trim($("#reportBeginDate").val());
                var reportEndTimestamp   = $.trim($("#reportEndDate").val());

                if((!reportBeginTimestamp && reportEndTimestamp) || (reportBeginTimestamp && !reportEndTimestamp)){
                    showErrorDialog("","上报开始时间和上报结束时间必须同时选择！");
                    return false;
                }

                if(reportBeginTimestamp && reportEndTimestamp) {
                    var reportDateStart = reportBeginTimestamp.replace("-", "/");//替换字符，变成标准格式
                    var reportDateEnd = reportEndTimestamp.replace("-", "/");//替换字符，变成标准格式
                    var d1 = new Date(Date.parse(reportDateStart));
                    var d2 = new Date(Date.parse(reportDateEnd));
                    if (d1 > d2) {
                        showErrorDialog("", "上报开始时间 不能大于 上报结束时间！");
                        return false;
                    }
                }

				filterChartFnc(cusId, mdlId, woId, lotId, pToolId, pOpeId,shiftId ,boatNumber,reportBeginTimestamp,
						reportEndTimestamp);
				$("#filterChartDialog").modal("hide");
				
				$("#cusIdSel").val(cusId);
				$("#mdlIdSel").val(BaseFnc.replaceSpace(mdlId));
				$("#woIdSel").val(woId);
				/*$("#lotIdSel").val(lotId);*/
				$("#eqptIdSel").val(pToolId);
				$("#opeIdSel").val(pOpeId);
		
				// $("#reportBeginDatepicker input").val(reportBeginDate);
				// $("#reportBeginTimepicker input").val(reportBeginTime);
				// $("#reportEndDatepicker input").val(reportEndDate)
				// $("#reportEndTimepicker input").val(reportEndTime);

			});

	// $("#filterChartDialog_fromTimestamp,#filterChartDialog_toTimestamp").datetimepicker({
	// format : "yyyy-mm-dd hh:mm:ss",
	// language:"zh-CN"
	// // forceParse:true,
	// // autoclose:true
	// })
	function showFilterChartDialog() {

		// 当没有管制图显示时，不能进行筛选
		if (GlobalBean.displayChartCount <= 0) {
			showErrorDialog("", "当前没有可以被筛选的管制图");
			return false;
		}

		var inTrx = {
			trx_id :"XPCCHTDT",
			action_flg:"D",
			col_typ : GlobalBean.selectedChart.col_typ,
			grp_no : GlobalBean.selectedChart.grp_no,
			chart_no : GlobalBean.selectedChart.chart_no,
			chart_typ : GlobalBean.selectedChart.chart_typ
		};

//		url = "distinctChartCondition";
		outTrx = comTrxSubSendPostJson(inTrx);
		/*outTrx = comSendAjax(_GET, url, inTrx).outPo;*/
		console.info(outTrx);
		if (outTrx.rtn_code == _NORMAL) {
			GlobalBean.chartDataCondition = outTrx.chartDataCondition;
		}

		FilterDialog.setCusId();
		FilterDialog.setMdlId($("#filterChartDialog_cusIdSel").val());
		FilterDialog.setWoId($("#filterChartDialog_mdlIdSel").val());
		FilterDialog.setOpeId();
		FilterDialog.setToolId($("#filterChartDialog_opeIdSel").val(), "00000");
		$("#filterChartDialog").modal("show");
	}
	$("#f12_btn").click(function() {
				showFilterChartDialog();
				
			});

    //初始化各个下拉框
    var initSelectFnc = {
        iniOpeSelect : function(){
            var inTrxObj = {
                trx_id     : "FBPBISOPE" ,
                action_flg : 'L'
            };
            var  outTrxObj = comTrxSubSendPostJson(inTrxObj);
            if(outTrxObj.rtn_code == "0000000" ) {
                GlobalBean.opeKey = new Array();
                var oaryA = outTrxObj.oary;
                for(var i = 0; i < oaryA.length; i++){
                    GlobalBean.opeKey.push({
                        ope_id : oaryA[i].ope_id,
                        ope_ver : oaryA[i].ope_ver
                    });
                    oaryA[i].dsc = oaryA[i].ope_id + ":" + oaryA[i].ope_dsc;
                }
                SelectDom.addSelectArr($("#opeIdSel"),outTrxObj.oary,["ope_id"],["ope_id"],"Y",true,false);
            }
        },

        iniToolSel: function(){
        	var fabId =  $.trim($("#fabIdSel").val());
        	var lineId =   $.trim($("#lineIdSel").val());
            var opeId = $.trim($("#opeIdSel").val());
            var opeVer = '00000';
			var iary2  = {
				fab_id_fk : fabId,
				bay_id :lineId,
                ope_id_fk : opeId,
                ope_ver : opeVer
			}
            var inObj2 = {
                trx_id : 'FBPBISTOL',
                action_flg : "Q",
                iary : [iary2]
            };
           var outObj2 = comTrxSubSendPostJson(inObj2);
            if(outObj2.rtn_code === "0000000"){
                SelectDom.initWithSpace($("#eqptIdSel"));
                SelectDom.addSelectArr($("#eqptIdSel"),outObj2.oary,["tool_id"],["tool_dsc"],"Y",true);
            }
        },

        initLineSel : function (){
            comAddValueByDataCateFnc("#lineIdSel","AREA","data_ext","data_desc",true);
		},

		initFabIdSel : function (){
            comAddValueByDataCateFnc("#fabIdSel","FBID","data_ext","data_desc",true);
        },

		//班别
		initShiftIdSel : function (){
            comAddValueByDataCateFnc("#shiftIdSel","SHIF","data_id","data_desc",true,false);
		},

        //初始化舟号
        initZhListFnc : function (){
        comAddValueByDataCateFnc("#boatNumber","ZH","data_id","data_desc",true,false);
    	}

    }

    //pecvd设备组加载舟号
    function initBoatNumber(){
        SelectDom.initWithSpace($("#boatNumber"));
        var toolId = $("#eqptIdSel").val();
        var iary  = {
            tool_id : toolId,

        }
        var inObj2 = {
            trx_id : 'FBPBISTOL',
            action_flg : "I",
            iary : [iary]
        };
        var outObj2 = comTrxSubSendPostJson(inObj2);
        if(outObj2.rtn_code === "0000000"){
            //设备组代码
            if(outObj2.oary[0].tool_group_id_fk === "$TPECVD"){
                initSelectFnc.initZhListFnc();
            }
        }
    };


    function initSel(){
        initSelectFnc.iniToolSel();
        initSelectFnc.initLineSel();7
        initSelectFnc.initFabIdSel();
        initSelectFnc.iniOpeSelect();
        initSelectFnc.initShiftIdSel();
    }

    initSel();
    $("#fabIdSel").on("change",initSelectFnc.iniToolSel);
    $("#lineIdSel").on("change",initSelectFnc.iniToolSel);
    $("#opeIdSel").on("change",initSelectFnc.iniToolSel);
    $("#eqptIdSel").on("change",initBoatNumber);

    // $("#opeIdSel").change(function(){
    //     initSelectFnc.iniToolSel();
    // });
})
